﻿using System.Collections;
using System.Collections.Generic;
using System.Net.Mail;
using System.Text;

namespace Convertor.Plugin.SendEmail
{
    class SendEmail
    {
        public static List<SendEmail> SmtpClientList = new List<SendEmail>();

        private string from;
        private string reply;
        private string displayName;
        private System.Text.Encoding bodyEncoding = System.Text.Encoding.Default;
        SmtpClient client;
        public SendEmail(SmtpClientViewModel v)
        {
            this.from = this.reply = v.Reply;
            this.displayName = v.DisplayName;
            client = new SmtpClient()
            {
                Host = v.Host,
                UseDefaultCredentials = v.UseDefaultCredentials,
                Port = v.Port,
                 EnableSsl = v.EnableSsl,
            };
            if (!v.UseDefaultCredentials)
            {
                client.Credentials = new System.Net.NetworkCredential(v.LoginName, v.LoginPassword);
            }
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            SmtpClientList.Add(this);
        }
        public override string ToString()
        {
            return client.Host;
        }
        /// <summary>
        /// 
        /// </summary>
        public void SendMail(string to, string subject, string body, bool isBodyHtml, ArrayList paths)
        {
            if (string.IsNullOrEmpty(from))
            {
                from = to;
            }
            if (string.IsNullOrEmpty(reply))
            {
                reply = to;
            }
            if (string.IsNullOrEmpty(displayName))
            {
                displayName = to;
            }
            //创建mailMessage对象 
            System.Net.Mail.MailMessage mail = new MailMessage();

            mail.From = new MailAddress(from, from, Encoding.Default);
            mail.To.Add(to);
            mail.Subject = subject;
            mail.Body = body;
            mail.IsBodyHtml = isBodyHtml;
            mail.BodyEncoding = bodyEncoding;
            mail.ReplyToList.Add(new MailAddress(reply));
            mail.From = new MailAddress(from, displayName);

            if (paths != null && paths.Count != 0)
            {
                foreach (string path in paths)
                {
                    Attachment data = new Attachment(path, System.Net.Mime.MediaTypeNames.Application.Octet);
                    mail.Attachments.Add(data);
                }
            }
            client.Send(mail);
        }
    }
}
